/**
 * @author kiyoshiro
 */

$(function() {
	var TIME_OUT = 3000

	$('.warn').addClass('ui-state-error').hide();

	$('#timeout-dialog').dialog( {
		autoOpen : false,
		modal : true
	});

	// ajax処理を意識したモーダルフォーム
	$('#create-table-dialog')
			.dialog(
					{
						autoOpen : false,
						/*
						 * height: 300, width: 350,
						 */
						modal : true,
						buttons : {
							"done" : function() {
								if (!$(this).dialog('option', 'disabled')) {
									$(this).dialog('disable');

									setTimeout(
											function() {
												if ($('#create-table-dialog')
														.dialog('isOpen')) {
													$('#create-table-dialog')
															.dialog('close');
													$('#timeout-dialog')
															.dialog('open');
												}
											}, TIME_OUT);

									$
											.getJSON(
													'kei3Table/put',
													{
														name : $('#table-name')
																.val()
													},
													function(result) {
														if (result.status == 'succcess'
																&& $(
																		'#create-table-dialog')
																		.dialog(
																				'isOpen')) {
															alert('add table');
															$(
																	'#create-table-dialog')
																	.dialog(
																			'close');
														} else if (result.status == 'input-invalid') {
															var form = $('#create-table-dialog');
															$(result.data)
																	.each(
																			function() {
																				form
																						.find(
																								'#' + this)
																						.fadeIn();
																			});
														} else {

														}
													});
								}
							},
							Cancel : function() {
								if (!$(this).dialog('option', 'disabled')) {
									$(this).dialog('close');
								}
							}
						},
						close : function() {
							$(this).find('.warn').hide();
							$(this).dialog('enable');
						}
					});

	$('#create-table').click(function() {
		// show dialog
			// $('#create-table-dialog').dialog('open');
			$.getJSON('table/put', {
				'table-name' : $('#table-name').val()
			}, function(result) {
				if (result.status == 'success') {
					// TODO:success
					$('#current-table-name').text(result.data.name);
					$('#current-table').attr('name', result.data.key);

				} else {
					// TODO:error
					alert(result.status);
				}
			});
		});
});
